// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import ResMgr from "./common/ResMgr";
import DBMgr from "./db/DBMgr";
import Global, { PLATFORM } from "./Global";

import asy = require("async");
import TickerMgr from "./ticker/TickerMgr";

const {ccclass, property} = cc._decorator;

@ccclass
export abstract default class StartUp extends cc.Component {

    private static _instance:StartUp = null;
    public static get instance():StartUp {
        return this._instance;
    }

    ///////////////////////////////////////////////////
    private _resLoadComplete;
    private _waitLoadRes:Array<string> = new Array<string>();
    @property(cc.Node)
    public uiRoot:cc.Node = null;
    @property(cc.Node)
    public gameRoot:cc.Node = null;
    @property(cc.Camera)
    public uiCamera:cc.Camera = null;
    @property(cc.Camera)
    public gameCamera:cc.Camera = null;
    @property(cc.Node)
    public renderTexture:cc.Node = null;

    onLoad() {
        StartUp._instance = this;
    }

    start() {
        this.initProcess();
    }

    update(dt) {
        TickerMgr.instance.doTick(dt);
    }

    //////////////////////////////////////////////
    protected initProcess() {

        if (this.uiRoot == null) {
            cc.log("游戏ui根节点没有指定");
            return;
        }

        if (this.gameRoot == null) {
            cc.log("游戏对象根节点没有指定");
            return;
        }
        
        cc.game.setFrameRate(Global.fps);
        let tasks = [];
        tasks.push(this.handleUrl.bind(this));
        tasks.push(this.initCamera.bind(this));
        tasks.push(this.initNet.bind(this));
        tasks.push(this.initPlatform.bind(this));
        tasks.push(this.initBurying.bind(this));
        tasks.push(this.initLoadRes.bind(this));
        
        tasks.push(this.startLoad.bind(this));
        tasks.push(this.initUserData.bind(this));
        tasks.push(this.startGame.bind(this));

        asy.eachSeries(tasks, (task, completedCallback)=>{
            task(completedCallback);
        }, () => {
            cc.log('启动任务全部完成');
        })

        /*this.handleUrl();
        this.initCamera();
        this.initNet();
        this.initPlatform();
        this.initBurying();
        this.initLoadRes();
        this.initUserData();
        this.startLoad();*/
    }

    //处理url参数
    private handleUrl(completedCallback) {
        let argsformat = {}
        var href: string = window.location.href;
        if (href) {
            var arr: Array<string> = href.split("?");
            if (arr.length > 1) {
                var allargs: Array<string> = arr[1].split("&");
                for (var i = 0; i < allargs.length; i++) {
                    var index = allargs[i].indexOf('=');
                    var key = allargs[i].slice(0, index);
                    var value = allargs[i].slice(index + 1, allargs[i].length);
                    argsformat[key] = value;
                }
            }
            if (argsformat["playerId"]) {
                Global.playerId = argsformat["playerId"];
            }
            if (argsformat["server"]) {
                Global.localUrl = "http://" + argsformat["server"];
                Global.url = "http://" + argsformat["server"];
                console.log("url--Ser:"+Global.url);
            }
            Global.isWebPlatform = true;//判断是浏览器
        }
        completedCallback();
    }

    //初始化相机设置
    protected initCamera(completedCallback) {
        completedCallback();
    }

    //初始化统计
    protected initBurying(completedCallback) {
        completedCallback();
        //BuryingMgr.event(BuryEnums.COCOS_START);//启动统计
    }
    //初始化平台
    protected initPlatform(completedCallback) {
        completedCallback();
        
    }
    //初始化网络部分
    protected initNet(completedCallback) {
        completedCallback();
    }
    //初始化需要加载的资源
    protected initLoadRes(completedCallback) {
        this.pushLoadRes("data/db");
        completedCallback();
    }
    //添加加载资源
    protected pushLoadRes(res:string) {
        this._waitLoadRes.push(res);
    }
    //更新进度
    protected onUpdatePercent(percent) {

    }
    //加载完单个资源响应
    protected loadResource(res) {
        if (res.name == "db") {
            DBMgr.parse();
        }
    }
    //初始化玩家信息
    protected initUserData(completedCallback) {
        completedCallback();
    }
    //初始化全局配置
    protected initGlobal(completedCallback) {
        completedCallback();
    }
    
    //启动游戏
    protected startGame(completedCallback) {
        completedCallback();
    }
    ////////////////////////////////////////////////////////////////////////////////////////////////////////
    private startLoad(completedCallback) {
        this._resLoadComplete = completedCallback;
        //completedCallback();
        if (this._waitLoadRes.length == 0) { 
            //this.startGame();
            return;
        }
        setTimeout(() => {
            ResMgr.loadResArray(this._waitLoadRes, this.progressHandler.bind(this), this.completedHandler.bind(this));
        }, 10);
        
    }

    private progressHandler(completedCount: number, totalCount: number, item: any) {
        this.onUpdatePercent(completedCount/totalCount);
    }

    private completedHandler(error: Error, resource: any[]) {
        if (error) {
            console.log("初始加载", error);
            return;
        }
        // ResMgr.cacheRes("ui/game", cc.SpriteAtlas);
        for (var i: number = 0; i < resource.length; i++) {
            this.loadResource(resource[i]);
        }
        //this.startGame();
        this._resLoadComplete && this._resLoadComplete();
    }

    
}
